<template>
  <div>
    <BasicTable @register="registerTable" class="!p-0">
      <template #paixuSlot>
        <div class="bg-light-50"><drag-outlined /></div>
      </template>

      <template #customTableHeader>
        <div class="mb-10px ml-10px">
          <RadioGroup
            button-style="solid"
            :size="'large'"
            v-model:value="langBtn"
            @change="handleModalSuccess"
          >
            <RadioButton :value="el.value" v-for="(el, index) in langList" :key="el.value"
              >{{ el.label }}
            </RadioButton>
          </RadioGroup>
        </div>
      </template>

      <template #form-created>
        <div :class="isHasAuth('40204') ? 'mr-2.5' : ''">
          <Button @click="openAddIpModalFun()" type="primary" v-if="isHasAuth('40204')">
            {{ $t('table.discountActivity.discountActivity_type_new_activity') }}
          </Button>
        </div>
      </template>
      <template #form-currentType>
        <a-input-group compact style="display: flex; width: 380px" class="t-form-label-com">
          <Select style="width: 40%" v-model:value="currentType" class="br-none">
            <SelectOption :value="'id'">ID</SelectOption>
            <SelectOption :value="'name'">
              {{ $t('table.discountActivity.discount_name') }}
            </SelectOption>
            <SelectOption :value="'updated_name'">
              {{ $t('table.risk.report_operate_people') }}
            </SelectOption>
          </Select>
          <Input
            style="width: 60%; margin-right: 10px"
            allowClear
            :placeholder="$t('common.inputText')"
            v-model:value="fromSearch"
          />
        </a-input-group>
      </template>
      <template #form-startDate="{ model, field }">
        <DatePicker
          v-model:value="model[field]"
          :disabledDate="disabledStartDate"
          @change="onStartDateChange"
        />
      </template>
      <template #group="{ record }">
        <!--文字' : '图片'-->
        <div v-if="record.group == 1">{{ getGroupLabel(record.group) }}</div>
        <div class="primary-color cursor" v-else @click="handleGroup(record)">{{
          getGroupLabel(record.group)
        }}</div>
      </template>
      <template #form-endDate="{ model, field }">
        <DatePicker
          v-model:value="model[field]"
          :disabledDate="disabledEndDate"
          @change="onEndDateChange"
        />
      </template>
      <template #action="{ record }">
        <template v-if="record.ty == 5 && isHasAuth('40210')">
          <span
            class="primary-color cursor"
            v-if="record.display == 2"
            @click="closeActiveState(record)"
          >
            {{ $t('table.risk.close_activity') }}
          </span>
        </template>

        <template v-else-if="isHasAuth('40210')">
          <span
            class="primary-color cursor mr-3"
            v-if="(record.state == 2 || record.state == 3) && record.display == 2"
            @click="closeActiveState(record)"
          >
            {{ $t('table.risk.close_activity') }}
          </span>
        </template>

        <span
          class="primary-color cursor"
          v-if="isHasAuth('40207')"
          @click="settingRecommend(record)"
        >
          {{
            record.recommend === 2
              ? $t('table.risk.close_activity_1')
              : $t('table.risk.close_activity_2')
          }}</span
        >
        <span
          class="px-3 cursor primary-color"
          v-if="isHasAuth('40204')"
          @click="EditFun(record)"
          >{{ $t('business.common_edit') }}</span
        >
        <span
          v-if="dayjs(record.start_at_tz).valueOf() < dayjs().valueOf()"
          class="cursor primary-color"
          @click="recordHandle(record)"
        >
          {{ $t('business.common_jl') }}
        </span>
        <span
          class="px-3 primary-color cursor"
          v-if="record.ty == 3"
          @click="handleRedenleoped(record)"
          >{{ $t('business.common_hb') }}</span
        >
      </template>
      <template #dataTimeSlot="{ record }">
        <div v-if="record.ty === 3">
          <div>
            {{ record['start_at_tz']?.split(' ')[0] }}
          </div>
          <div>
            {{ record['end_at_tz']?.split(' ')[0] }}
          </div>
        </div>
        <div v-else-if="record.ty != 5">
          <div>
            {{ record['start_at_tz']?.split(' ')[0] }}
          </div>
          <div>
            {{ record['end_at_tz']?.split(' ')[0] }}
          </div>
        </div>
        <div v-else>-</div>
      </template>
      <template #showDataTime="{ record }">
        <div v-if="record.ty === 3">
          <div>
            {{ record['display_start_at_tz']?.split(' ')[0] }}
          </div>
          <div>
            {{ record['display_end_at_tz']?.split(' ')[0] }}
          </div>
        </div>
        <div v-else>
          <div>
            <!-- {{ dayjs(record.display_start_at * 1000).format('YYYY-MM-DD HH:mm:ss') }} -->
            {{ record['display_start_at_tz']?.split(' ')[0] }}
          </div>
          <div>
            <!-- {{ dayjs(record.display_end_at * 1000).format('YYYY-MM-DD HH:mm:ss') }} -->
            {{ record['display_end_at_tz']?.split(' ')[0] }}
          </div>
        </div>
      </template>
      <template #activeState="{ record }">
        <Switch
          v-if="record.ty != 5 && isHasAuth('40208')"
          v-model:checked="record.state"
          :checkedValue="1"
          :unCheckedValue="2"
          :disabled="record.state == 2 || record.state == 3"
          @change="handleActiveState(record)"
        />
        <Switch
          v-else
          v-model:checked="record.display"
          :disabled="true"
          :checkedValue="1"
          :unCheckedValue="2"
        />
      </template>
      <template #showState="{ record }">
        <Switch
          :disabled="!isHasAuth('40208')"
          v-model:checked="record.display"
          :checkedValue="1"
          :unCheckedValue="2"
          @change="handleDisplayState(record)"
        />
      </template>
      <template #recommendState>
        <Switch v-model:checked="recommendSwich" />
      </template>
    </BasicTable>
    <recordList @register="recordTable" />
    <detailModal @register="registerDetailModal" />
    <RedEnvelope @register="registerRedModal" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, computed, watchEffect, onBeforeUnmount } from 'vue';
  import { BasicTable, useTable } from '/@/components/Table';
  import { columns, getActiviTy, schemas } from './index.data';
  import { Button } from '/@/components/Button';
  import { DragOutlined } from '@ant-design/icons-vue';
  import {
    InputGroup,
    Select,
    SelectOption,
    Input,
    DatePicker,
    FormItemRest,
    message,
    Switch,
    Space,
    RadioGroup,
    RadioButton,
  } from 'ant-design-vue';
  import { useRouter } from 'vue-router';
  //import { getRiskBlackList, deletRiskBlack } from '/@/api/risk';
  //import AddIpModal from '../../common/components/addIpModal.vue';
  import { useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  //import { openConfirm } from '/@/utils/confirm';
  //import { setDateParmas } from '/@/utils/dateUtil';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    getPromoList,
    updatePromoClose,
    updatePrompClose,
    updatePromoDisplay,
    updateMerchantClose,
  } from '/@/api/activity';
  import { promoActivitySort } from '/@/api/sys';
  import recordList from '../recordList/index.vue';
  import { getGroupLabel } from '../../common/setting';
  import detailModal from '../../common/components/detailModal.vue';
  import { ADDraggableRow } from '/@/utils';
  import { useLocalList } from '/@/settings/localeSetting';
  import RedEnvelope from '../redEnvelope/index.vue';
  import { isHasAuth } from '@/utils/authFunction';
  import { cloneDeep } from 'lodash-es';

  const $router = useRouter();
  interface FormModel {
    start_time: Date | null;
    end_time: Date | null;
  }
  const model = ref<FormModel>({
    start_time: null,
    end_time: null,
  });
  const { t } = useI18n();

  const localeList = useLocalList();

  const langList = ref(
    localeList.map((item) => {
      return {
        label: t('common.common_' + item.event),
        value: item.event,
      };
    }),
  );

  const langBtn = ref('' as string);
  const fromSearch = ref('' as string);
  const currentType = ref('id' as string);
  const activeSwich = ref(false as any);
  const recommendSwich = ref(false as any);
  const [registerDetailModal, { openModal: openDetailModal }] = useModal();
  const disabledStartDate = (date) => {
    let end_time: any = null;
    if (dayjs(model.value.end_time).valueOf()) {
      end_time = model.value.end_time?.valueOf();
    } else {
      end_time = dayjs().endOf('days').valueOf();
    }
    return date.valueOf() > end_time;
  };

  const disabledEndDate = (date) => {
    return (
      date.valueOf() > dayjs().endOf('days').valueOf() ||
      date.valueOf() <= dayjs(model.value.start_time).valueOf()
    );
  };
  const onStartDateChange = (value) => {
    model.value.start_time = value;
  };

  const onEndDateChange = (value) => {
    model.value.end_time = dayjs(value).endOf('days');
  };

  let dataSource = ref<any>([]);
  const _dataSource = ref<any>([]);

  const [registerTable, { reload, clearSelectedRowKeys, setTableData }] = useTable({
    customRow: isHasAuth('40206')
      ? (record, index) => ADDraggableRow(dataSource.value, index, setTableData, sortTable)
      : undefined,
    api: getPromoList,
    columns: columns,
    bordered: true,
    useSearchForm: true,
    showIndexColumn: false,
    formConfig: {
      schemas,
      showAdvancedButton: false,
      actionColOptions: {
        class: 't-form-label-com',
        span: 1,
      },
      showResetButton: false,
    },
    beforeFetch: (params) => {
      params['flag'] = 1;
      params['lang'] = langBtn.value;

      if (params.category === 0) {
        if (!('ty' in params)) {
          // ty 字段不存在
        } else if (params.ty === 0) {
          delete params.ty; // 删除 ty 字段
        }
      } else {
        params.ty =
          params.ty === 0
            ? getActiviTy(params.category) // 根据 category 获取活动值
            : params.ty.toString(); // 转为字符串
      }
      delete params.category; // 删除 category 字段

      if (currentType.value) {
        params[currentType.value] = fromSearch.value;
      }
      return params;
    },
    afterFetch: (data) => {
      updateLangList(data);
      clearSelectedRowKeys();
      dataSource.value = data;
      _dataSource.value = cloneDeep(data);
    },
  });
  const [recordTable, { openModal }] = useModal();
  const [registerRedModal, { openModal: openRed }] = useModal();
  function handleRedenleoped(record) {
    openRed(true, { data: record });
  }
  // const isRecord = computed(()=>{
  //   return model.value.start_time
  // })
  async function sortTable(targetWork: any, tempSource: any) {
    // const data = await reload(); // 获取当前数据列表

    const param = {
      id: tempSource.id,
      index_id: targetWork.id,
      sort_before: tempSource.seq_id,
      sort_after: targetWork.seq_id,
    };

    console.log('param:', param);

    // 发送排序请求
    try {
      const { status, data: responseData } = await promoActivitySort({
        lang: langBtn.value,
        ...param,
      });

      if (status) {
        message.success(responseData);
      } else {
        message.error(responseData);
      }

      // 重新加载数据
      reload();
    } catch (e) {
      console.log(e);
    }
  }

  function updateLangList(list) {
    if (langBtn.value) return;
    const currentLangList = list.map((item) => JSON.parse(item.lang));
    const mergeLangList = currentLangList.flat();
    const filterMergeLangList = [...new Set(mergeLangList)];
    langList.value = localeList
      .filter((lang) => filterMergeLangList.includes(lang.event))
      .map((item) => {
        return {
          label: t('common.common_' + item.event),
          value: item.event,
        };
      });
    langBtn.value = langList.value[0].value as string;
    reload();
  }
  function openAddIpModalFun() {
    $router.push({ name: 'InsertActive' });
  }
  function recordHandle(data) {
    openModal(true, data);
  }
  watchEffect(() => console.log(model.value.start_time, 'time--------'));

  async function closeActiveState(v) {
    //console.log(v.id);
    const { status, data } = await updateMerchantClose({ pid: v.id });
    if (status) {
      message.success(data);
    }
    handleModalSuccess();
  }

  async function handleActiveState(v) {
    //console.log(v.id);
    const { status, data } = await updatePromoClose({ pid: v.id });
    if (status) {
      message.success(data);
    }
    handleModalSuccess();
  }

  async function handleDisplayState(v) {
    const { status, data } = await updatePromoDisplay({ pid: v.id, display: v.display });
    if (status) {
      message.success(data);
    }
    handleModalSuccess();
  }
  function handleGroup(data) {
    openDetailModal(true, data);
  }
  function EditFun(record) {
    $router.push({ name: 'InsertActive', state: { id: record.id } });
  }
  async function settingRecommend(value) {
    const state = value.recommend === 1 ? 2 : 1;
    const { status, data } = await updatePrompClose({ pid: value.id, recommend: state });
    if (status) {
      message.success(data);
      reload();
    } else {
      message.error(data);
    }
  }
  function handleModalSuccess() {
    reload();
  }

  onMounted(() => {
    console.log(activeSwich.value);
  });
  onBeforeUnmount(() => {
    langBtn.value = '';
  });
</script>
<style lang="less" scoped>
  ::v-deep(.ant-radio-button-wrapper) {
    min-width: 88px;
    text-align: center;
  }

  .color-E46 {
    color: #5451ff;
  }

  .color-B42 {
    color: #42b3f2;
  }

  ::v-deep(.columnSelectBar) {
    cursor: pointer;

    td:first-child {
      cursor: pointer;
    }
  }
</style>
